package com.guo.hui.config;

import com.guo.hui.dao.MyMenuMapper;
import com.guo.hui.dao.MyUserMapper;
import com.guo.hui.entity.MyMenu;
import com.guo.hui.entity.MyRole;
import com.guo.hui.entity.MyUser;
import com.guo.hui.util.EncryptionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @ClassName UserServiceInfo
 * @Description TODO
 * @Author zhengguohui
 * @Date 2018/9/3 11:24
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private MyUserMapper userMapper;
    @Autowired
    private MyMenuMapper MyMenu;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        MyUser myUser = userMapper.findMyUser(username);
        List<MyMenu> menus = MyMenu.findByUid(myUser.getId());
        Set<GrantedAuthority> grantedAuthorities = new HashSet<>();
        for (MyMenu menu : menus) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(menu.getMenuCode());
            grantedAuthorities.add(grantedAuthority);
        }
        User user = new User(myUser.getUsername(), EncryptionUtil.getBCryptData(myUser.getPassword()), grantedAuthorities);
        return user;
    }
}
